package sq.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sq.dao.Address;
import sq.dao.Cart;
import sq.dao.SchoolAddress;
import sq.dao.User;
import sq.repository.AddressRepository;
import sq.repository.SchoolAddressRepository;
import sq.repository.UserRepository;
import sq.service.AddressService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: sunquan
 * @Date: 2018/3/28
 * @Time: 22:07
 */
@Service
@Transactional
public class AddressServiceImpl implements AddressService{
@Autowired
private SchoolAddressRepository schoolAddressRepository;
@Autowired
private AddressRepository addressRepository;
@Autowired
private UserRepository userRepository;
    @Override
    public List<SchoolAddress> findSchoolAddress() {
        List<SchoolAddress> schoolAddressList=schoolAddressRepository.findAll();
        return schoolAddressList;
    }

    @Override
    public void updateAddress(Integer userId,String phone,String username,Integer schoolAddress,String addressDetail) {
        Address address1=null;
        address1=addressRepository.findAddressByUserId(userId);
        if(address1==null){
            Address address2=new Address();
            address2.setUserId(userId);
            address2.setPhone(phone);
            address2.setUsername(username);
            address2.setSchoolAddress(schoolAddress);
            address2.setAddressDetail(addressDetail);
            addressRepository.save(address2);
        }else{
            addressRepository.updateAddressByAddressId(
                    userId,
                    phone,
                    username,
                    schoolAddress,
                    addressDetail
            );
        }
    }

    @Override
    public Address findAddress(HttpServletRequest request) {
        HttpSession session = request.getSession();
        try {
            String userName = session.getAttribute("userSession").toString();
            User user = userRepository.findUserByUsername(userName);
            Integer userId = user.getUserId();
            Address address=addressRepository.findAddressByUserId(userId);
            return address;
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return null;
    }
}
